package com.xcap.security.datasourceauthentication.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xcap.security.datasourceauthentication.util.JwtUtil;
import com.xcap.security.datasourceauthentication.vo.HttpResult;
import com.xcap.security.datasourceauthentication.vo.MySecurityUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 使用jwts生成token jwt
 */
@Component
@Slf4j
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    //使用次工具进行序列化
    @Resource
    private ObjectMapper objectMapper;
    @Resource
    JwtUtil jwtUtil;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //从认证对象中获取认证用户的信息
       MySecurityUser securityUser=(MySecurityUser) authentication.getPrincipal();

        String userInfo = objectMapper.writeValueAsString(securityUser.getSysUser());
//获取 用户的权限信息
        List<SimpleGrantedAuthority> authorities = (List<SimpleGrantedAuthority>)securityUser.getAuthorities();
        // todo 这里可以改成lambda表达式
        ArrayList<String> strings = new ArrayList<>();
        for (SimpleGrantedAuthority authority : authorities) {
            strings.add(authority.getAuthority());
        }
        List<String> collect = authorities.stream().map(SimpleGrantedAuthority::getAuthority).collect(Collectors.toList());
        log.info("collect1111:{}",collect);

        //创建jwt
        String token = jwtUtil.createToken(userInfo, strings);
        //返回给前端 token
        HttpResult httpResult = HttpResult.builder().code(200).msg("ok").data(token).build();
        PrintWriter writer = response.getWriter();
        writer.write(objectMapper.writeValueAsString(httpResult));
        writer.flush();
    }
}
